import json
import os
from decimal import Decimal

from django import http
from django.conf import settings
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import ListCreateAPIView, RetrieveAPIView, ListAPIView, CreateAPIView, UpdateAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet, ModelViewSet
from alipay import AliPay
from rest_framework.permissions import IsAdminUser

from fjr.models import SKU
from meiduo_drf.utils.views import LoginRequiredJSONMixin
from users_lab.models import Address
from .models import OrderInfo, OrderGoods, Payment
from .serializer import OrderCommitSerializer, OrderSettleSerializer, UnCommentGoodsSerializer, CommentGoodsSerializer, \
    PaymentSerializer, OrderIdRetrieveSerializer, OrderSettleOrderGoodsSerializer
from django.utils import timezone
# 自定义分页类
class StandardResultPagination(PageNumberPagination):
    # 指定分页的默认页容量
    page_size = 4
    # 指定获取分页数据时，页容量参数的名称
    # 注意：下面这个属性不要写成：page_query_param
    page_size_query_param = 'pagesize'
    # 指定分页时的最大页容量
    max_page_size = 5

from django.views import View


class AlipayView(View):
    # GET /orders/(?P<order_id>\d+)/payment/
    # permission_classes = [IsAdminUser]

    def get(self, request, order_id):

        # 校验order_id是否存在
        try:
            order = OrderInfo.objects.get(order_id=order_id)    # 这里做了点假
        except OrderInfo.DoesNotExist:
            return http.JsonResponse({'code': 400, 'errmsg': '参数order_id错误'})

        # 对接支付宝的支付接口
        # 创建AliPay的SDK对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,  # 应用的ID
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 使用AliPay的SDK对象调用支付的接口函数接口，得到收银台扫码登录路径order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,  # 美多商城维护的订单号
            total_amount=str(order.total_amount),  # 实付款
            subject="美多商城%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,  # 支付成功后的回调地址
        )

        alipay_url = settings.ALIPAY_URL + '?' + order_string

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'alipay_url': alipay_url})


class PaymentView(UpdateAPIView):
    lookup_field = 'order_id'
    queryset = Payment.objects.all()
    serializer_class = PaymentSerializer


class UnCommentGoodsView(RetrieveAPIView):
    lookup_field = 'order_id'
    queryset = OrderGoods.objects.all()     #.filter(order_id=lookup_field)
    serializer_class = UnCommentGoodsSerializer


class CommentGoodsView(CreateAPIView):
    queryset = OrderGoods.objects.all()
    serializer_class = CommentGoodsSerializer


class OrderCommitView(ModelViewSet):
    queryset = OrderInfo.objects.all()
    # serializer_class = OrderCommitSerializer

    def get_serializer_class(self):
        if self.action == 'list':
            return OrderCommitSerializer
        if self.action == 'create':
            return OrderIdRetrieveSerializer

    # queryset_order = OrderInfo.objects.all()
    # 2. 将权限类型的数据序列化并返回
    # serializer = OrderIdRetrieveSerializer(queryset_order, many=True)
    #
    # pagination_class = StandardResultPagination  # 指定分页器

    def create(self, request, *args, **kwargs):

        # 获取登录用户
        user = request.user
        redis_conn = get_redis_connection('carts')
        item_dict = redis_conn.hgetall('carts_%s' % user.id)
        cart_selected = redis_conn.smembers('selected_%s' % user.id)
        cart = {}
        for sku_id in cart_selected:
            cart[int(sku_id)] = int(item_dict[sku_id])
        user.cart = cart
        address = Address.objects.get(id=user.id)
        # 生成订单编号：年月日时分秒+用户编号
        order_id = timezone.localtime().strftime('%Y%m%d%H%M%S') + ('%09d' % user.id)
        data = {
            'user_id':user.id,
            'address':address.id,
            'pay_method': 2,
            'order_id': order_id,
            'total_amount': Decimal(cart[int(sku_id)]),
        }
        # serializer = OrderIdRetrieveSerializer(data=data)
        # serializer.is_valid(raise_exception=True)
        # serializer.save()

        return Response(data)


        #
        # redis_conn = get_redis_connection('carts')
        # item_dict = redis_conn.hgetall('carts_%s' % user.id)
        # cart_selected = redis_conn.smembers('selected_%s' % user.id)
        # cart = {}
        # for sku_id in cart_selected:
        #     cart[int(sku_id)] = int(item_dict[sku_id])
        # user.cart = cart
        # 生成订单编号：年月日时分秒+用户编号
        # order_id = timezone.localtime().strftime('%Y%m%d%H%M%S') + ('%09d' % user.id)
        # dict = {
        #     'order_id': order_id
        # }
        # # address = Address.objects.get(id=1)
        # return Response(dict)
        # sku = SKU.objects.all()
        # order = OrderInfo.objects.all()
        # sku_count = user.cart[int(sku.id)]
        # order.total_amount += (sku_count * sku.price)
        #
        # order.total_amount += (sku_count * sku.price)
        # request.data['user_id'] = user.id
        # request.data['order_id'] = order_id
        # request.data['address'] = 1
        # request.data['total_amount'] = order.total_amount
        #
        # serializer = self.get_serializer(data=request.data)
        # serializer.is_valid(raise_exception=True)
        # self.perform_create(serializer)
        # headers = self.get_success_headers(serializer.data)

        # user = self.request.user
        # 清除购物车中已结算的商品

        # item_dict = redis_conn.hgetall('carts_%s' % user.id)
        # cart_selected = redis_conn.smembers('selected_%s' % user.id)
        # cart = {}
        # for sku_id in cart_selected:
        #     cart[int(sku_id)] = int(item_dict[sku_id])
        # carts[sku.id]
        #
        # redis_conn.hdel('carts_%s' % user.id, *cart_selected)
        # redis_conn.srem('selected_%s' % user.id, *cart_selected)
        # order = OrderInfo.objects.create(
        #     order_id=order_id
        # )
        # order.save()
        # OrderInfo.objects.order_id = order_id
        # OrderInfo.save()
        # return Response(serializer.data)
        # return Response(dict)

        # return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)




class test():
    def __init__(self,skus):
        self.skus = skus

class OrderSettleView(ListAPIView):
    # GET /orders/settlement/
    # queryset = OrderInfo.objects.all()
    serializer_class = OrderSettleSerializer
    def get_queryset(self):
        # def get(self,request):
        #     super().get(self, request)
        #     # 从Redis购物车中查询出被勾选的商品信息
        user = self.request.user

        redis_conn = get_redis_connection('carts')
        item_dict = redis_conn.hgetall('carts_%s' % user.id)
        cart_selected = redis_conn.smembers('selected_%s' % user.id)
        cart = {}
        for sku_id in cart_selected:
            cart[int(sku_id)] = int(item_dict[sku_id])
        sskus = SKU.objects.filter(id__in=cart.keys())
        for sku in sskus:
            sku.count = cart[sku.id]
        # t = test(sskus)
        user.skus = sskus
        user.cart = cart
        # return t
        return user

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset)
        return Response(serializer.data)


